package com.mi.fastbird.common.spring.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 上下文工具类
 *
 * @author 王永吉
 * @date 2019/8/21
 */
@Slf4j
@Component
public class ContextKit implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ContextKit.applicationContext = applicationContext;
        log.info(".............. 上下文注入完成 ..............");
    }

    /**
     * 获取上下文
     */
    public static ApplicationContext getContext() throws BeansException {
        return ContextKit.applicationContext;
    }

    /**
     * 通过实例变量名获取实例
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 通过class获取单个Bean实例
     */
    public static <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param beanName 实例变量名
     * @param tClass   类型
     */
    public static <T> T getBean(String beanName, Class<T> tClass) {
        return applicationContext.getBean(beanName, tClass);
    }

    /**
     * 是否存在实例
     *
     * @param beanName 实例变量名
     */
    public static boolean contains(String beanName) {
        return applicationContext.containsBean(beanName);
    }

    /**
     * 是否为单例
     *
     * @param beanName 实例变量名
     */
    public static boolean isSingle(String beanName) {
        return applicationContext.isSingleton(beanName);
    }
}
